package com.blyat.xsoft.kernel.component.pool;

import org.apache.commons.pool2.ObjectPool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @Auther: syh
 * @Date: 2020/8/3
 * @Description:
 */
public class ConnectionInvokeHandler<T extends Connection> implements InvocationHandler {

    private T connection;
    private T proxyConnection;
    private final ObjectPool<T> pool;

    public ConnectionInvokeHandler(final ObjectPool<T> pool, T connection) {
        this.pool = pool;
        this.connection = connection;
    }

    public void setProxyConnection(T proxyConnection) {
        this.proxyConnection = proxyConnection;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if (method.getName().equals("getTargetConnection")) {
            return connection;
        }

        if ("close".equals(method.getName())) {
            pool.returnObject(proxyConnection);
            connection = null;
            proxyConnection = null;
            return null;
        }
        return method.invoke(connection, args);
    }
}
